package ${basePackage}.service.imports.${module};

<#if !exportSame>import java.util.Date;</#if>
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import ${basePackage}.adapter.logger.LoggerImportTaskAdapter;
import ${basePackage}.adapter.${module}.${entityName}Adapter;
import ${basePackage}.adapter.validate.IValidateAdapter;
import ${basePackage}.enums.OperatorTypeEnum;
import ${basePackage}.enums.imports.task.ImportTaskEventEnum;
import ${basePackage}.imports.IImportBusinessService;
import ${basePackage}.pojo.bo.${module}.${currModule}.${entityName}ImportBo;
import ${basePackage}.pojo.bo.${module}.${currModule}.${entityName}ImportStopBo;
import ${basePackage}.pojo.dao.logger.imports.task.LoggerImportTaskInsertDo;
import ${basePackage}.pojo.dao.${module}.${currModule}.${entityName}InsertBatchDo;
import ${basePackage}.pojo.dao.${module}.${currModule}.${entityName}InsertBatchItemDo;
import ${basePackage}.pojo.mo.${module}.${currModule}.${entityName}ImportMo;
import ${basePackage}.pojo.mso.logger.imports.task.LoggerImportTaskQueueMso;
import ${basePackage}.pojo.vo.${module}.${currModule}.${entityName}ImportVo;
import ${basePackage}.pojo.vo.${module}.${currModule}.${entityName}ImportStopVo;
import ${basePackage}.rabbit.RabbitConstant;
<#if !exportSame>import ${basePackage}.rabbit.RabbitQueue;</#if>
import ${basePackage}.service.BaseService;
import ${basePackage}.service.LoggerService;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.JsonUtils;

@Service
@Api(value="${tableComment!''}导入服务", author="${username}", date="${date}", version="1.0.0")
public class ${entityName}ImportService extends BaseService implements IImportBusinessService<${entityName}ImportMo, ${entityName}ImportBo>, RabbitConstant{
	
	@Autowired
	@ApiField("${tableComment!''}公共服务")
	private ${entityName}Adapter ${entitySampleName}Adapter;
	
	@Autowired
	@ApiField("导出任务服务")
	private LoggerImportTaskAdapter loggerImportTaskAdapter;
	
	@Autowired
	@ApiField("操作日志服务")
	private LoggerService loggerService;
	<#if !exportSame>
	
	@Autowired
	@ApiField("Rabbit Mq发送消息服务")
	private RabbitQueue rabbitQueue;
	</#if>
	
	@Autowired
	@ApiField("表单验证公共操作")
	private IValidateAdapter validateAdapter;
	
	<#if !exportSame>
	
	@ApiMethod(value="导入会员(不要加事务，否则有可能导致任务还没创建，但是队列已经消费查询，最终导致导入报错)", params=@ApiField("导入业务实体，包含附件信息"), returns=@ApiField("导入结果Vo->result:{0：未被导入，1：已成功导入}"))
	public ${entityName}ImportVo imports(${entityName}ImportBo importBo) {
		ExceptionUtils.trueException(loggerImportTaskAdapter.existsTasking(this.getUserId(), ${entitySampleName}Adapter.getModule()), "task.is.currently.executing", "有${tableComment!''}导入");
		Date date=new Date();
		LoggerImportTaskInsertDo task=new LoggerImportTaskInsertDo();
		task.setName("${tableComment!''}");
		task.setModule(${entitySampleName}Adapter.getModule());
		task.setDocumentType("excel");
		task.setStatus((byte)0);
		task.setStartTime(date);
		task.setImportBeanClass(this.getClass().getName());
		task.setImportModelClass(${entityName}ImportBo.class.getName());
		task.setImportData(JsonUtils.toJson(importBo));
		task.setResult((byte)0);
		int result=loggerImportTaskAdapter.save(task, false);//保存任务，不用加事务，防止队列消费的时候还没保存完数据
		rabbitQueue.sendMessage(IMPORT_EXCHANGE_NAME, IMPORT_ROUTE_KEY, new LoggerImportTaskQueueMso(task.getId(), ImportTaskEventEnum.START, this.getHeader(tokenConfig.getKeyName()), getLanguage()));//发送导出队列
		return new ${entityName}ImportVo(task.getId(), result);
	}
	
	@ApiMethod(value="停止导出${tableComment!''}", params=@ApiField("停止导出对象"))
	public ${entityName}ImportStopVo stop(${entityName}ImportStopBo importStopBo){
		rabbitQueue.sendMessage(IMPORT_STOP_EXCHANGE_NAME, IMPORT_STOP_ROUTE_KEY, new LoggerImportTaskQueueMso(importStopBo.getId(), ImportTaskEventEnum.STOP, this.getHeader(tokenConfig.getKeyName()), getLanguage()));//发送停止导出队列
		return new ${entityName}ImportStopVo(1);
	}
	</#if>
	
	@Override
	@ApiMethod(value="获取导出模板的类类型", returns=@ApiField("导出模板类类型"))
	public Class<${entityName}ImportMo> getModule(){
		return ${entityName}ImportMo.class;
	}
	
	@Override
	@ApiMethod(value="导入开始时执行")
	public void start() {
		
	}
	
	@Override
	@ApiMethod(value="导入行数据验证，请再此处处理完所有的验证，否则可能导致数据导入一部分", params = {@ApiField("需验证的行数据"), @ApiField("此数据在excel中的行次（从零开始）"), @ApiField("操作导出的用户token"), @ApiField("导入条件")})
	public void validate(${entityName}ImportMo rowData, int rowIndex, String token, ${entityName}ImportBo condition) {
		rowData.setRowNumber(rowIndex+1);
		validateAdapter.validate(${entitySampleName}Adapter.getModule(), "import", rowData, this.getUser(token), ${entitySampleName}Adapter);//验证表单
	}
	
	@Override
	@ApiMethod(value="导入数据批量处理，批次数据根据nocos配置确定批次大小", params = {@ApiField("批次数据"), @ApiField("此列表在excel中的开始行次（从零开始）"), @ApiField("操作导出的用户token"), @ApiField("导入条件")})
	public void handleBatch(List<${entityName}ImportMo> rowList, int startRowIndex, String token, ${entityName}ImportBo condition) {
		List<${entityName}InsertBatchItemDo> batchList=this.convertPojoList(rowList, ${entityName}InsertBatchItemDo.class);
		Long userId=this.getUserId(token);
		for (${entityName}InsertBatchItemDo batchItem : batchList) {
			batchItem.setCreateUser(userId);
			batchItem.setChangeUser(userId);
		}
		${entitySampleName}Adapter.saveBatch(new ${entityName}InsertBatchDo(batchList), false);//批量插入数据
		int index=0;
		for (${entityName}ImportMo importData : rowList) {
			long id=batchList.get(index).getId();
			loggerService.writer(id, ${entitySampleName}Adapter.getModule(), OperatorTypeEnum.IMPORT, token, importData);//记录日志
			index++;
		}
	}
	
	@Override
	@ApiMethod(value="结束导入时触发，如清理临时缓存等", params = {@ApiField("用户token")})
	public void finish(String token) {
		validateAdapter.finish();
	}
}